package cn.gailvlun.gll.presentation.chat.vm

import android.arch.lifecycle.ViewModel
import cn.gailvlun.gll.chatlib.bean.SystemNotification
import cn.gailvlun.gll.chatlib.db.ChatDB2
import io.reactivex.Flowable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.realm.Realm
import io.realm.RealmResults
import io.realm.Sort
import java.util.concurrent.TimeUnit


class SystemNotificationActivityViewModel : ViewModel {

    private var realm : Realm?

    val systemNotificationFlowable: Flowable<RealmResults<SystemNotification>>

    constructor() : super() {
        this.realm = Realm.getInstance(ChatDB2.getConfiguration())

        systemNotificationFlowable = realm!!.where(SystemNotification::class.java)


                .sort("created", Sort.DESCENDING)
                .findAllAsync()
                .asFlowable()
                .filter { it.isLoaded }
                .sample(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
    }

    fun readAllNotification() {
        val results = realm!!.where(SystemNotification::class.java)


                .equalTo("unread", true)
                .findAll()
        realm!!.executeTransaction { realm ->
            for (noti in results) {
                noti.isUnread = false
            }
        }
    }

    override fun onCleared() {
        realm?.close()
        realm = null

        super.onCleared()
    }
}